/*
 * Copyright (c) 2009-2024 Arm Limited. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*============================ INCLUDES ======================================*/

#define __USER_SCENE2_IMPLEMENT__
#include "arm_2d_scenes.h"

#if defined(RTE_Acceleration_Arm_2D_Helper_PFB)

#ifdef RTE_Acceleration_Arm_2D_Scene2

#include <stdlib.h>
#include <string.h>

#if defined(__clang__)
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wunknown-warning-option"
#   pragma clang diagnostic ignored "-Wreserved-identifier"
#   pragma clang diagnostic ignored "-Wsign-conversion"
#   pragma clang diagnostic ignored "-Wpadded"
#   pragma clang diagnostic ignored "-Wcast-qual"
#   pragma clang diagnostic ignored "-Wcast-align"
#   pragma clang diagnostic ignored "-Wmissing-field-initializers"
#   pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#   pragma clang diagnostic ignored "-Wmissing-prototypes"
#   pragma clang diagnostic ignored "-Wunused-variable"
#   pragma clang diagnostic ignored "-Wgnu-statement-expression"
#   pragma clang diagnostic ignored "-Wdeclaration-after-statement"
#   pragma clang diagnostic ignored "-Wunused-function"
#   pragma clang diagnostic ignored "-Wmissing-declarations"
#   pragma clang diagnostic ignored "-Wimplicit-int-conversion" 
#elif __IS_COMPILER_ARM_COMPILER_5__
#   pragma diag_suppress 64,177
#elif __IS_COMPILER_IAR__
#   pragma diag_suppress=Pa089,Pe188,Pe177,Pe174
#elif __IS_COMPILER_GCC__
#   pragma GCC diagnostic push
#   pragma GCC diagnostic ignored "-Wformat="
#   pragma GCC diagnostic ignored "-Wpedantic"
#   pragma GCC diagnostic ignored "-Wunused-function"
#   pragma GCC diagnostic ignored "-Wunused-variable"
#   pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
#endif

/*============================ MACROS ========================================*/

#if __GLCD_CFG_COLOUR_DEPTH__ == 8

#   define c_tileCMSISLogo          c_tileCMSISLogoGRAY8

#elif __GLCD_CFG_COLOUR_DEPTH__ == 16

#   define c_tileCMSISLogo          c_tileCMSISLogoRGB565

#elif __GLCD_CFG_COLOUR_DEPTH__ == 32

#   define c_tileCMSISLogo          c_tileCMSISLogoCCCA8888
#else
#   error Unsupported colour depth!
#endif

/*============================ MACROFIED FUNCTIONS ===========================*/
#undef this
#define this (*ptThis)

/*============================ TYPES =========================================*/
/*============================ GLOBAL VARIABLES ==============================*/

extern const arm_2d_tile_t c_tileCMSISLogo;
extern const arm_2d_tile_t c_tileCMSISLogoMask;
extern const arm_2d_tile_t c_tileCMSISLogoA2Mask;
extern const arm_2d_tile_t c_tileCMSISLogoA4Mask;
/*============================ PROTOTYPES ====================================*/
/*============================ LOCAL VARIABLES ===============================*/

/*! define dirty regions */
IMPL_ARM_2D_REGION_LIST(s_tDirtyRegions, static)

    /* a dirty region to be specified at runtime*/
    ADD_REGION_TO_LIST(s_tDirtyRegions,
        0  /* initialize at runtime later */
    ),
    
    /* add the last region:
        * it is the top left corner for text display 
        */
    ADD_LAST_REGION_TO_LIST(s_tDirtyRegions,
        .tLocation = {
            .iX = 0,
            .iY = 0,
        },
        .tSize = {
            .iWidth = 0,
            .iHeight = 8,
        },
    ),

END_IMPL_ARM_2D_REGION_LIST(s_tDirtyRegions)

/*============================ IMPLEMENTATION ================================*/

static void __on_scene2_load(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);

}

static void __after_scene2_switching(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);

}

static void __on_scene2_depose(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);
    
    ptScene->ptPlayer = NULL;
    
    /* reset timestamp */
    arm_foreach(int64_t,this.lTimestamp, ptItem) {
        *ptItem = 0;
    }

    if (!this.bUserAllocated) {
        __arm_2d_free_scratch_memory(ARM_2D_MEM_TYPE_UNSPECIFIED, ptScene);
    }
}

/*----------------------------------------------------------------------------*
 * Scene 2                                                                    *
 *----------------------------------------------------------------------------*/

static void __on_scene2_background_start(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);

}

static void __on_scene2_background_complete(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);

}

void word_run(arm_2d_scene_t *ptScene);
static void __on_scene2_frame_start(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);
    
    word_run( ptScene);

}

static void __on_scene2_frame_complete(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);

#if 0
    /* switch to next scene after 3s */
    if (arm_2d_helper_is_time_out(3000, &this.lTimestamp[0])) {
        arm_2d_scene_player_switch_to_next_scene(ptScene->ptPlayer);
    }
#endif
}

static void __before_scene2_switching_out(arm_2d_scene_t *ptScene)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)ptScene;
    ARM_2D_UNUSED(ptThis);

}

void  draw_my_word(void *pTarget,                                  
                                const arm_2d_tile_t *ptTile,
                                arm_2d_region_t my_region,    
                                bool bIsNewFrame);

static
IMPL_PFB_ON_DRAW(__pfb_draw_scene2_handler)
{
    user_scene_2_t *ptThis = (user_scene_2_t *)pTarget;
    arm_2d_size_t tScreenSize = ptTile->tRegion.tSize;

    ARM_2D_UNUSED(ptTile);
    ARM_2D_UNUSED(bIsNewFrame);
    ARM_2D_UNUSED(tScreenSize);
    
    arm_2d_fill_colour(ptTile, NULL, GLCD_COLOR_BLACK);
    
    arm_2d_canvas(ptTile, __top_canvas) {
    /*-----------------------draw the foreground begin-----------------------*/
        
        
        draw_my_word( pTarget,                                  
                                 ptTile,
                                  __top_canvas,    
                                  bIsNewFrame);


        /* draw text at the top-left corner */

        arm_lcd_text_set_target_framebuffer((arm_2d_tile_t *)ptTile);
        arm_lcd_text_set_font(&ARM_2D_FONT_6x8.use_as__arm_2d_font_t);
        arm_lcd_text_set_draw_region(NULL);
        arm_lcd_text_set_colour(GLCD_COLOR_WHITE, GLCD_COLOR_BLACK);
        arm_lcd_text_location(0,0);
        //arm_lcd_puts("Scene 2");

    /*-----------------------draw the foreground end  -----------------------*/
    }
    ARM_2D_OP_WAIT_ASYNC();

    return arm_fsm_rt_cpl;
}
void my_world_init();
ARM_NONNULL(1)
user_scene_2_t *__arm_2d_scene2_init(   arm_2d_scene_player_t *ptDispAdapter, 
                                        user_scene_2_t *ptThis)
{
    bool bUserAllocated = false;
    assert(NULL != ptDispAdapter);

    s_tDirtyRegions[dimof(s_tDirtyRegions)-1].ptNext = NULL;

    /* get the screen region */
    arm_2d_region_t tScreen
        = arm_2d_helper_pfb_get_display_area(
            &ptDispAdapter->use_as__arm_2d_helper_pfb_t);

    /* initialise dirty region 0 at runtime
     * this demo shows that we create a region in the centre of a screen(320*240)
     * for a image stored in the tile c_tileCMSISLogoMask
     */
    arm_2d_align_centre(tScreen, c_tileCMSISLogoMask.tRegion.tSize) {
        s_tDirtyRegions[0].tRegion = __centre_region;
    }

    s_tDirtyRegions[dimof(s_tDirtyRegions)-1].tRegion.tSize.iWidth 
                                                        = tScreen.tSize.iWidth;
    
    if (NULL == ptThis) {
        ptThis = (user_scene_2_t *)
                    __arm_2d_allocate_scratch_memory(   sizeof(user_scene_2_t),
                                                        __alignof__(user_scene_2_t),
                                                        ARM_2D_MEM_TYPE_UNSPECIFIED);
        assert(NULL != ptThis);
        if (NULL == ptThis) {
            return NULL;
        }
    } else {
        bUserAllocated = true;
    }
    memset(ptThis, 0, sizeof(user_scene_2_t));

    *ptThis = (user_scene_2_t){
        .use_as__arm_2d_scene_t = {

            /* the canvas colour */
            .tCanvas = {GLCD_COLOR_WHITE}, 

            /* Please uncommon the callbacks if you need them
             */
            .fnOnLoad       = &__on_scene2_load,
            .fnScene        = &__pfb_draw_scene2_handler,
            //.fnAfterSwitch  = &__after_scene2_switching,

            /* if you want to use predefined dirty region list, please uncomment the following code */
            //.ptDirtyRegion  = (arm_2d_region_list_item_t *)s_tDirtyRegions,
            

            //.fnOnBGStart    = &__on_scene2_background_start,
            //.fnOnBGComplete = &__on_scene2_background_complete,
            .fnOnFrameStart = &__on_scene2_frame_start,
            //.fnBeforeSwitchOut = &__before_scene2_switching_out,
            .fnOnFrameCPL   = &__on_scene2_frame_complete,
            .fnDepose       = &__on_scene2_depose,

            .bUseDirtyRegionHelper = false,
        },
        .bUserAllocated = bUserAllocated,
    };

    /* ------------   initialize members of user_scene_2_t begin ---------------*/


    /* ------------   initialize members of user_scene_2_t end   ---------------*/

    arm_2d_scene_player_append_scenes(  ptDispAdapter, 
                                        &this.use_as__arm_2d_scene_t, 
                                        1);
    my_world_init();
    return ptThis;
}

//============================================================================
#include "ff.h" 
#include "key.h"
void  draw_string_2d(uint16_t iX,uint16_t iY,char font_size,char *strin,
    void *pTarget,                                  
                                const arm_2d_tile_t *ptTile);
    
    
typedef struct word_t{
    uint32_t lseek;
    uint16_t current_num;
    
    char english[17];
    char chinese[17];

}word_t;
word_t my_word;

void read_world();
void my_world_init(){
    my_word.current_num = 0;
    my_word.lseek = 0;
    read_world();
}
void read_world(){
    FIL file;  // 文件对象
    FRESULT res;  // FatFs返回结果
    char out_buff[128];
    uint32_t rd_len;  
    
    res = f_open(&file,  "/TXT/word.txt", FA_READ);
    if (res == FR_OK) {
        res = f_lseek(&file,my_word.lseek );
        if (res == FR_OK) {
                res = f_read(&file, out_buff, 128, &rd_len);
        }
    }else{
        return;
    }
    f_close(&file) ; 
    char i = 0;
    char char_num = 0;
    while(1){
        if(((out_buff[i] >= 'a') && (out_buff[i] <= 'z'))  || ((out_buff[i] >= 'A') && (out_buff[i] <= 'Z')) ){
            my_word.english[char_num] = out_buff[i];
            char_num++;
        }
        i++;
        if(out_buff[i] == '('){
            my_word.english[char_num] = 0;
            i++;
            break;
        }
    }
    char j = 0;
    char_num = 0;
    while(1){
        if( out_buff[i] >= 0x80    ){
            my_word.chinese[char_num] = out_buff[i];
            my_word.chinese[char_num+1] = out_buff[i+1];
            i+=2;
            char_num+=2;
        }else{
            i++;
        }
        if(out_buff[i] == ')'){
            my_word.chinese[char_num] = 0;
            i++;
            break;
        }
    }
    my_word.lseek += i;
}
void word_read_next(){
    read_world();
    my_word.current_num++;
}
void word_run(arm_2d_scene_t *ptScene){
     char key;
    key = get_g_key_num();
    if(key){
        switch (key){
            case 1:
                word_read_next();
                //book_list_previous();
                //my_book.current_lseek += my_book.add_lseek;
            break;
            case 3:
                //book_list_next();
            break;
            case 2:
                //my_book.list_read_flag = 1;
                __arm_2d_scene0_init( &DISP0_ADAPTER ,NULL);
                arm_2d_scene_player_switch_to_next_scene(ptScene->ptPlayer);
            break;
        }
        set_g_key_num(0);
    }
}
void  draw_my_word(void *pTarget,                                  
                                const arm_2d_tile_t *ptTile,
                                arm_2d_region_t my_region,    
                                bool bIsNewFrame){
     arm_2d_dock_top( my_region,  30 ) {
         arm_2d_dock_vertical( __top_region,  12 ) {
             draw_string_2d(__top_region.tLocation.iX, __top_region.tLocation.iY, 16,my_word.english,  pTarget,  ptTile); 
         }
          
     }
     arm_2d_dock_bottom(my_region,  40)   {
         arm_2d_align_centre(__bottom_region, 16*3,16 ){
             
             draw_string_2d(__centre_region.tLocation.iX, __centre_region.tLocation.iY, 16,my_word.chinese,  pTarget,  ptTile); 
         }
     }
}

#if defined(__clang__)
#   pragma clang diagnostic pop
#endif

#endif

#endif

